<template>
  <a-menu v-model:selectedKeys="selectedKeys" mode="horizontal" @click="toJump">
    <a-menu-item v-for="item of menus" :key="item.href">
      <span>{{ item.name }}</span>
    </a-menu-item>
  </a-menu>
</template>

<script lang="ts">
  import { defineComponent, inject, ref, watch } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { BaseObject, BaseArray } from '@/types/global';
  import { load, loadAll } from '@/service/site-docs';

  export default defineComponent({
    name: 'TopMenu',
    setup() {
      const router = useRouter();
      const route = useRoute();
      const config = inject('config') as BaseObject;
      const menus: BaseArray = ref([]);
      const selectedKeys: BaseArray = ref([]);
      const configMenus = config?.site?.topMenus;
      let loadPromises: BaseArray = [];

      function active() {
        const hash = window.location.hash.replace('#', '');
        selectedKeys.value = [];
        menus.value.forEach((item) => {
          if (hash === item.href) {
            selectedKeys.value = [item.href];
          }
        });
      }
      function toJump({ key }) {
        if (key[0] === '/') {
          router.push(key);
        } else {
          window.open(key);
        }
      }

      if (configMenus) {
        loadPromises = configMenus.map((item: string | BaseObject) => {
          if (typeof item === 'string') {
            return load(item);
          }
          return Promise.resolve(item);
        });
      } else {
        loadPromises = loadAll();
      }
      Promise.all(loadPromises as Promise<BaseObject>[]).then((list) => {
        menus.value = list.map((item) => {
          return item.href
            ? item
            : {
                name: item.attributes.title,
                href: `/doc/${item.name}`,
              };
        });
        active();
      });

      watch(route, active);

      return {
        selectedKeys,
        menus,
        toJump,
      };
    },
  });
</script>
